import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_elm/json/response_item.dart';
import 'package:flutter_elm/network/business_api.dart';
import 'package:flutter_elm/network/business_api.dart';
import 'package:flutter_elm/network/cart_api.dart';
import 'package:flutter_elm/network/cart_api.dart';
import 'package:provider/provider.dart';

import '../components/elmBottomNavigatorBar.dart';
import '../json/business_item.dart';
import '../json/cart_item.dart';
import '../json/item_model.dart';
import '../network/user_api.dart';
import '../store/global_data.dart';

class BusinessListPage extends StatefulWidget {
  const BusinessListPage({super.key, required this.title});
  final String title;

  @override
  State<BusinessListPage> createState() => _BusinessListPageState();
}

class _BusinessListPageState extends State<BusinessListPage> {
  BusinessApi businessApi = BusinessApi();
  CartApi cartApi = CartApi();

  Future<List<BusinessItem>?> getBusinessListData(int type) async{
    ResponseItem<List<BusinessItem>?> resBusiness = await businessApi.getBusinessByType(type);
    List<BusinessItem>? businessList = resBusiness.data;
    if(resBusiness.data!=null){
      String userId = Provider.of<GlobalData>(context, listen: false).getUserId();
      if(userId!=""){
        //貌似使用 list.map的方法，程序根本不进去 :)，只能用最原始的for循环去做
        for(int i = 0;i<businessList!.length;i++){
          var resCart = await cartApi.findCartsByUidAndBid(userId, businessList[i].businessId);
          if(resCart.code==200){
            List<CartItem> cartList = resCart.data!;
            for(int j=0; j<cartList.length; j++){
              businessList[i].userCartCount = businessList[i].userCartCount! + cartList[j].quantity;
            }
          }//反之就是 没有加到购物车，直接 默认值0就行
        }
      }
      return businessList;
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    int type = ModalRoute.of(context)?.settings.arguments as int;

    return Scaffold(
        appBar: AppBar(
        backgroundColor: Colors.blueAccent.shade400,
        title: Text("${widget.title}",style: TextStyle(color: Colors.white),),
    centerTitle: true,
    // 取消左上角返回箭头
    automaticallyImplyLeading: false,
    ),
    bottomNavigationBar: ElmBottomNavigatorBar(),
    body: FutureBuilder(
      future: getBusinessListData(type),
      builder: (context, snpashot){
        switch(snpashot.connectionState){
          case ConnectionState.done:
            List<BusinessItem>? businessList = snpashot.data;
            if(businessList != null){
              return ListView.builder(
                itemCount: businessList.length,
                itemBuilder: (context, index){
                  return GestureDetector(
                    onTap: (){toBusinessInfoOrLogin(businessList[index]);} ,
                    child: BlistListViewItem(item: businessList[index]),
                  );
                },
              );
            }else{
              return Center(child: Text("没有数据"),);
            }
          default:
            return Center(child: Text("数据加载中..."),);
        }
      },
    )
    );
  }

  void toBusinessInfoOrLogin(BusinessItem businessItem){
    String userId = Provider.of<GlobalData>(context, listen: false).getUserId();
    if(userId==""){
      Navigator.pushNamed(context, "login");
    }else{
      Navigator.pushNamed(context, "business_info",arguments: businessItem);
    }
  }
}






















class StackTopRightNumberWithImgOld extends StatelessWidget {
  const StackTopRightNumberWithImgOld({super.key, required this.item});

  final BusinessItem item;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 120,
      height: 120,
      decoration: BoxDecoration(
        // borderRadius: BorderRadius.circular(10),
        // color: Colors.grey
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.memory(
              Base64Decoder().convert(item.businessImg.split(",")[1]),
              scale: 1.2,
            ),
          ),
          item.userCartCount==0?SizedBox():Positioned(
              top: 2,
              right: 0,
              child: Container(
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100),
                    color: Colors.red
                ),
                width: 25,
                height: 25,
              )
          ),
          item.userCartCount==0?SizedBox():Positioned(
              top: 0,
              right: 6.3,
              child: Text("${item.userCartCount}",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                ),
              )),
        ],
      ),
    );
  }
}


class StackTopRightNumberWithImg extends StatelessWidget {
  const StackTopRightNumberWithImg({super.key, required this.item});

  final BusinessItem item;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 120,
      height: 120,
      decoration: BoxDecoration(
        // borderRadius: BorderRadius.circular(10),
        // color: Colors.grey
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(10),
            child: Image.memory(
              Base64Decoder().convert(item.businessImg.split(",")[1]),
              scale: 1.2,
            ),
          ),
          item.userCartCount==0?SizedBox():Positioned(
            //消除按钮自带的外边距效果。首先：可以设置为负数。其次，可以看出MaterialButton自带的外边距就是10
              right: -10, top: -9,
              child: CircleWithCenterSingleNum(num: item.userCartCount!, textColor: Colors.white, circleColor: Colors.red,)
          ),
        ],
      ),
    );
  }
}




class CircleWithCenterSingleNum extends StatelessWidget {
  const CircleWithCenterSingleNum({super.key, required this.num, required this.textColor,required this.circleColor});
//注意：如果是要改大小的话，还得琢磨
  final int num;
  final Color textColor;
  final Color circleColor;


  @override
  Widget build(BuildContext context) {
    return Container(
      child: MaterialButton(
        onPressed: (){},
        //背景颜色
        color: circleColor,
        //设置一个完整的圆大小
        height: 28, minWidth:28, padding: EdgeInsets.all(0),
        //圆角边框
        shape: const RoundedRectangleBorder(side:BorderSide.none,borderRadius: BorderRadius.all(Radius.circular(200),),),
        //取消自带的点击水波效果
        splashColor: Colors.transparent, focusColor: Colors.transparent,highlightColor: Colors.transparent,
        //取消自带的阴影效果
        //按钮的阴影 //按钮按下时的阴影高度//未设置点击时的阴影高度
        elevation: 0,highlightElevation: 0,disabledElevation: 0.0,
        child: Text("${num}",style: TextStyle(color: textColor,fontSize: 20),),
      ),
    );
  }
}








class BlistListViewItem extends StatelessWidget {
  const BlistListViewItem({super.key, required this.item});

  final BusinessItem item;

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.symmetric(vertical: 15, horizontal: 5),
        decoration: BoxDecoration(
          // color: Colors.grey
          border: Border(bottom: BorderSide(width: 1.0, color: Colors.grey.shade300)),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            StackTopRightNumberWithImg(item:item),
            Padding(padding: EdgeInsets.only(right:15)),
            Expanded(
                child: Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(item.businessName,style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),),
                      Padding(padding: EdgeInsets.only(bottom: 10)),
                      Text("￥${item.starPrice}起送 | ￥${item.deliveryPrice}配送",style: TextStyle(fontSize: 15),),
                      Padding(padding: EdgeInsets.only(bottom:10)),
                      Text(item.businessExplain),
                    ],
                  ),
                ))
          ],
        )
    );
  }
}


